package org.geektimes.web.mvc.servlet;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @author :   chuan
 * @date :   2021/03/23
 */
@HandlesTypes(MyWebMvcInitializer.class)
public class MyWebMvcServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {

        List<MyWebMvcInitializer> initializers = new LinkedList<>();

        if (c != null) {
            for (Class<?> waiClass : c) {

                if (!waiClass.isInterface()
                        && !Modifier.isAbstract(waiClass.getModifiers())
                        && MyWebMvcInitializer.class.isAssignableFrom(waiClass)) {
                    try {
                        initializers.add((MyWebMvcInitializer)waiClass.newInstance());
                    }
                    catch (Throwable ex) {
                        throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                    }
                }
            }

            if (initializers.isEmpty()) {
                ctx.log("No MyWebMvcServletContainerInitializer types detected on classpath");
                return;
            }

            for (MyWebMvcInitializer initializer : initializers) {
                initializer.onStartup(ctx);
            }
        }

    }
}
